﻿using Microsoft.Xrm.Sdk;
using QueueManager.Helper.Crm;
using QueueManager.Helper;
using System.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace QueueManagerWeb
{
  public partial class ClientInformation : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      var serverConnect = new CustomCrmServiceHelper();
      var config = serverConnect.GetServerConfiguration();

      // Connect to the Organization service. 
      // The using statement assures that the service proxy will be properly disposed.
      var serviceProxy = CustomCrmServiceHelper.GetOrganizationProxy(config);

      // This statement is required to enable early-bound type support.
      serviceProxy.EnableProxyTypes();
      var service = (IOrganizationService)serviceProxy;

      var crmHelper = new CrmHelper(service);

      //Verify that the paramaters are there
      if (string.IsNullOrEmpty(Request.QueryString["key"]) || string.IsNullOrEmpty(Request.QueryString["t"]) || string.IsNullOrEmpty(Request.QueryString["s"]))
      {
        //If not, hide all fields.
        ctlHeader.Visible = false;
        cmdSubmit.Visible = false;
        ctlContainer.Visible = false;
        ctlWelcomeText.Visible = false;
        ctlRequiredInfoText.Visible = true;
        return;
      }

      if (!IsPostBack)
      {
        //Disable on postback
        cmdSubmit.Attributes.Add("onclick", "document.body.style.cursor = 'wait'; this.disabled = true; " + ClientScript.GetPostBackEventReference(cmdSubmit, string.Empty) + ";");

        //Retrieve the e-mail
        var eMail = GetEMail();

        if (eMail != null)
        {
          txtEMail.Text = eMail.From.First().AddressUsed;

          //Now try to work out the first and last name
          if (!string.IsNullOrEmpty(eMail.SubmittedBy))
          {
            //Find and get the name from the string (which should be "FirstName LastName <name@domain.com>", but you never know).
            var name = crmHelper.ResolveNames(eMail.SubmittedBy);

            txtFirstName.Text = name.FirstName;
            txtLastName.Text = name.LastName;

            //Set focus
            if (string.IsNullOrEmpty(txtFirstName.Text))
            {
              txtFirstName.Focus();
            }
            else if (string.IsNullOrEmpty(txtLastName.Text))
            {
              txtLastName.Focus();
            }
            else
            {
              txtCompany.Focus();
            }

          }
          else
          {
            //Set focus to first textbox
            txtFirstName.Focus();
          }

          //If cookies are support then store in session to avoid having to retrieve it again on postback
          if (Request.Browser.Cookies)
          {
            Session["email"] = eMail;
          }

        }
        else
        {
          //Zero or more e-mails returned, display message and bail out
          cmdSubmit.Visible = false;
          ctlContainer.Visible = false;
          ctlWelcomeText.Visible = false;
          ctlNotFoundText.Visible = true;
        }
      }

    }


    protected void cmdSubmit_Click(object sender, System.EventArgs e)
    {
      var serverConnect = new CustomCrmServiceHelper();
      var config = serverConnect.GetServerConfiguration();

      // Connect to the Organization service. 
      // The using statement assures that the service proxy will be properly disposed.
      var serviceProxy = CustomCrmServiceHelper.GetOrganizationProxy(config);

      // This statement is required to enable early-bound type support.
      serviceProxy.EnableProxyTypes();
      var service = (IOrganizationService)serviceProxy;

      var crmHelper = new CrmHelper(service);

      var email = default(Email);
      var objContact = default(Contact);

      //Bail out if not valid
      if (!this.IsValid)
        return;

      //Get the email using either session or from the server again
      if (Session["email"] == null)
      {
        email = GetEMail();
      }
      else
      {
        email = (Email)Session["email"];
      }

      //Hide fields if we couldn't retrieve the e-mail
      if (email == null || Convert.ToString(Session["submitted"]) == email.ActivityId.Value.ToString())
      {
        ctlHeader.Visible = false;
        cmdSubmit.Visible = false;
        ctlContainer.Visible = false;
        ctlWelcomeText.Visible = false;
        ctlRequiredInfoText.Visible = true;
        return;
      }

      //Create a new contact using the information provided
      objContact = new Contact();

      //Set properties, this can be modified to the fields you need.
      objContact.FirstName = txtFirstName.Text;
      objContact.LastName = txtLastName.Text;
      objContact.MobilePhone = txtMobile.Text;
      objContact.EMailAddress1 = txtEMail.Text;
      objContact.JobTitle = txtJobTitle.Text;
      objContact.Description = "Information created by the user. Company name specified: " + txtCompany.Text;

      //Alternative e-mail
      if (!string.IsNullOrEmpty(txtAltEMail.Text))
      {
        objContact.EMailAddress2 = txtAltEMail.Text;
      }

      //Attempt to resolve the parent account automatically
      if (ConfigurationManager.AppSettings["resolveparent"] == "true")
      {
        crmHelper.ResolveParentAccount(objContact, txtEMail.Text, ConfigurationManager.AppSettings["resolveparent-notify"], ConfigurationManager.AppSettings["resolveparent-from"]);
      }

      //Create contact
      var guid = crmHelper.Create(objContact);

      //Update email
      {
        email.From.First().PartyId = new EntityReference(Contact.EntityLogicalName, guid);
      }

      //Reset tracking token
      email.TrackingToken = null;

      //Update e-mail
      //crmHelper.Update(email);

      //Reoute the e-mail back to the queue for processing
      crmHelper.RouteEMail(email, new Guid(Request.QueryString["s"]), new Guid(Request.QueryString["t"]));

      //Modify texts
      cmdSubmit.Visible = false;
      ctlContainer.Visible = false;
      ctlWelcomeText.Visible = false;
      ctlThanksText.Visible = true;
      Session["submitted"] = email.ActivityId.Value.ToString();

    }

    private Email GetEMail()
    {
      var serverConnect = new CustomCrmServiceHelper();
      var config = serverConnect.GetServerConfiguration();

      // Connect to the Organization service. 
      // The using statement assures that the service proxy will be properly disposed.
      using (var serviceProxy = CustomCrmServiceHelper.GetOrganizationProxy(config))
      {
        // This statement is required to enable early-bound type support.
        serviceProxy.EnableProxyTypes();
        var service = (IOrganizationService)serviceProxy;

        var crmHelper = new CrmHelper(service);

        //Get the e-mail using the token submitted
        var email = crmHelper.GetEmail(Request["key"]);
        if (email != null)
        {
          if (email.From.FirstOrDefault().PartyId == null)
          {
            return email;
          }
        }
      }
      return null;
    }

    protected void Page_Error(object sender, System.EventArgs e)
    {
      LogHelper.Log("Error rendering UpdateClientInformation.", Context.Error, LogHelper.LogType.Exception);

      ctlHeader.Visible = false;
      cmdSubmit.Visible = false;
      ctlContainer.Visible = false;
      ctlWelcomeText.Visible = false;
      ctlRequiredInfoText.Visible = false;
      ctlError.Visible = true;

    }


  }
}